﻿<template>

    <div v-loading="isLoading">

      <custom-field-form size="small" :fields="[{id:'id',name:'评价模型',colSpan:16, component:{id:'data-select',data:modelList,change:loadModelInfo}}]"
            :data="queryConditon"
      >
        <el-button size="small" @click="importConfigVisible=true">导入配置</el-button>
        <el-button size="small" @click="exportConfig">导出配置</el-button>
      </custom-field-form>
      <el-tabs v-if="modelInfo&&modelInfo.id" type="border-card">
        <el-tab-pane label="录入参数">
          <el-col span="10">
            <span>评价模型录入分类</span>
            <query-table :table-max-height="tableMaxHeight" v-if="modelInfo" ref="record_query_table" :page-size="-1" :columns="tableColumns"
                         :query-fields="modelQueryFields"
                         base-url="/table"
                         show-index></query-table>
          </el-col>
          <el-col span="14">
            <template v-if="modelInfo&&currentInputTable.id&&currentInputTable.id.length>0">
              <span>录入指标关联 - {{currentInputTable.name}}</span>
              <query-table :table-max-height="tableMaxHeight" ref="record_field_query_table" :page-size="-1" :columns="fieldColumns"
                           :query-fields="fieldQueryFields"
                           :detail-fields="inputRefInfoFields"
                           base-url="/settings/model_param_ref"
                           update-url="/settings/model_param_ref/save"
                           :detailDialogLoadData="false"
                           show-index></query-table>
            </template>
            <el-empty v-else description="请选择对应分类"></el-empty>
          </el-col>
        </el-tab-pane>
        <el-tab-pane label="结果导出">
          <div v-if="modelInfo">
          <span>评价结果导出数据</span>
              <query-table :key="'result_export:'+modelInfo.id" :table-max-height="tableMaxHeight" ref="compute_unit_query_table" :page-size="-1" :columns="exportColumns"
                           :query-fields="modelQueryFields"
                           :detail-fields="exportRefInfoFields"
                           base-url="/settings/model_export_ref"
                           update-url="/settings/model_export_ref/save"
                           :detailDialogLoadData="false"
                           show-index></query-table>
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-dialog title="导入信息"  element-loading-text="正在处理..." :visible.sync="importConfigVisible"
                 :close-on-click-modal="false">
        <el-form :model="configInfo">

          <el-form-item label="评价模型" :label-width="formLabelWidth">
            <el-input v-model="modelInfo.name" autocomplete="off" disabled></el-input>
          </el-form-item>
          <el-form-item label="数据文件" :label-width="formLabelWidth">
            <upload type="single"
                    :file-list="configInfo.fileList"></upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="importConfigVisible=false">取 消</el-button>
          <el-button type="success" @click="importConfig">导 入</el-button>
        </div>
      </el-dialog>

    </div>

</template>

<script>
import DataSelect from "../../components/data-select";
import CustomFieldForm from "../../components/custom-field-form";
export default {
  name: "ModelDataRef",
  components: {CustomFieldForm, DataSelect},
  props:{
    pageHeight:{

    }
  },
  data() {
    return {
      queryConditon:{},
      modelList:[],
      modelInfo: {},
      configInfo:{fileList:[]},
      isLoading: false,
      formLabelWidth: '120px',
      inputFieldList: [],
      inputFieldDlgVisible: false,
      importConfigVisible:false,
      inputField: {computeUnit: {ref: ''}, dataType: 'number', defaultValue: ''},
      currentInputTable: {},
      // refParamSourceMap: {},//关联参数来源集合
      refParamIdMap: {},//默认值集合
      computeUnitMap:{},

      //录入分类展示列信息
      tableColumns: [
        {id: 'name', name: '名称', align: 'left'},

        {
          id: 'single', name: '年份相关', width: 100, showOverflowTooltip: true,
          formatter: (val) => {
            if (val) {
              return '不相关';
            }
            return '相关';
          }
        },
        {id: 'needLastYear', name: '上年数据',
          width: 80,
          formatter: (val) => {
            if (val) {
              return '需要';
            }
            return '不需要';
          }
        },
        {
          id: 'operation', name: '操作', type: 'button', width: 100,
          align: 'right',
          children: [
            // {text: '查看', operation: 'view',
            //   isHide:(row) =>{
            //     return this.modelEditable;
            //   }
            // },
            {text: '指标列表', click: this.loadInputFieldList},

          ]
        },
      ],

      //录入字段展示列信息
      fieldColumns: [
        {id: 'fieldName', name: '指标名称', align: 'left'},
        {id: 'fieldDataType', name: '数据类型',type:'meta',source:'data-type', width: 80,},
        {id: 'fieldUnit', name: '指标单位',type:'meta',source:'unit-type', width: 80,},
        {id: 'paramSource', name: '关联来源',type:'name-display',dataUrl:'/settings/model_param_ref/ref/group', width: 180,},
        {id: 'paramId', name: '关联参数',type:'name-display',dataUrl:'/settings/model_param_ref/ref/data', width: 100, showOverflowTooltip: true},

        // {id: 'createTime', name: '关联时间', width: 150,},
        // {id: 'createUser', name: '关联人', type: 'user', width: 80, showOverflowTooltip: true},
        {
          id: 'operation', name: '操作', type: 'button', width: 130,
          align: 'right',
          children: [
            {text: '查看', operation: 'view',
              isHide:(row) =>{
                return this.checkPermission('model_param:map');
              }
            },
            {text: '编辑', operation: 'edit',permission:'model_param:map',

            },
            {
              text: '重置', type: 'danger', operation: 'delete',permission:'model_param:map',
            },
          ]
        },
      ],

      //导出字段展示列信息
      exportColumns: [
        {id: 'paramName', name: '项目指标',  align: 'left'},
        // {id: 'fieldDataType', name: '数据类型',type:'meta',source:'data-type', width: 80,},
        // {id: 'fieldUnit', name: '指标单位',type:'meta',source:'unit-type', width: 80,},
        // {id: 'paramSource', name: '关联来源',type:'meta',source:'model-param-ref-source', width: 100,},
        {id: 'sourceId', name: '计算指标', width: 100},
        // {id: 'sourceType', name: '计算指标类型', width: 100,component:{id:'meta-select',type:'compute-type'}},
        // {id: 'extractType', name: '提取方式', width: 100,type:'meta',source:'compute-data-extract-type'},
        {id: 'yearRelated', name: '年份相关', width: 100,formatter: (val) => {
            if (val) {
              return '相关';
            }
            return '不相关';
          }},

        // {id: 'createTime', name: '关联时间', width: 150,},
        // {id: 'createUser', name: '关联人', type: 'user', width: 80, showOverflowTooltip: true},
        {
          id: 'operation', name: '操作', type: 'button', width: 130,
          align: 'right',
          children: [
            {text: '查看', operation: 'view',
              isHide:(row) =>{
                return this.checkPermission('model_param:map');
              }
            },
            {text: '编辑', operation: 'edit',permission:'model_param:map',

            },
            {
              text: '重置', type: 'danger', operation: 'delete',permission:'model_param:map',
            },
          ]
        },
      ],

      inputRefInfoFields: [{
        id: 'fieldName',
        name: '指标名称',
        disabled:true,
        colSpan: 12,
      }, {
        id: 'fieldDataType',
        name: '数据类型',
        component: {
          id:'meta-select',
          type: 'data-type',
        },
        colSpan: 12,disabled:true
      },
        {
        id: 'paramSource',
        name: '关联参数来源',
          // disabled: true,
        component:{
          id:'data-select',
          dataUrl:'/settings/model_param_ref/ref/group'
        },
        colSpan: 12,
      },
        {
        id: 'paramId',
        name: '关联参数',
        // parent:'paramSource',
        component: {
          id: 'data-select',
          // dataUrl:'/settings/model_param_ref/ref/data',
          dataUrl:'/settings/model_param_ref/ref/data?paramSource=${paramSource}',
          // getDataUrl:(data) =>{
          //   //非自定义输入的关联参数来源会提供dataUrl来进行数据加载
          //   if(this.refParamSourceMap&&this.refParamSourceMap[data.paramSource]) {
          //     return this.refParamSourceMap[data.paramSource].dataUrl;
          //   }
          //   return null;
          // },
          load:(dataList,fieldData) => {
            let map = {};
            for (let item of dataList) {
              this.refParamIdMap[item.id] = item;
              //注意此处用code而不是用id
              // map[item.code] = item;
              map[item.id] = item;
              //判断是否年份相关
              if (item.yearRelated) {
                item.name = item.name
              }
            }
          }
        },
        colSpan: 12,
        isHide:(data)=>{
          //如果关联参数来源是自定义输入，则隐藏
          return data.paramSource=='input';
        }
      }, {
        id: 'yearDataFillType',
        name: '年份数据填充',
        component: {
          id: 'meta-select',
          type:'year-data-fill-type',
        },
        defaultValue: 'all_year',
        colSpan: 12,
        isHide:(data)=>{
          //年份无关或者年份相关分类但默认值为年份相关时不需要展示
          return this.currentInputTable.single||!this.isDefaultValueSingle(data.paramSource,data.paramId);
        }
      }
      ],
      exportRefInfoFields: [{
        id: 'paramId',
        name: '项目指标id',
        disabled:true,
        hide:true,
        colSpan: 24,
      },{
        id: 'paramName',
        name: '项目指标',
        disabled:true,
        colSpan: 24,
      },{
        id: 'yearRelated',
        name: '年份相关',
        disabled:true,
        component: {
          id:'data-select',
          data:[{id:true,name:'相关'},{id:false,name:'不相关'}]
        },
        colSpan: 24,
      },
      //   {
      //   id: 'fieldDataType',
      //   name: '数据类型',
      //   component: {
      //     id:'meta-select',
      //     type: 'data-type',
      //   },
      //   colSpan: 12,disabled:true
      // },
      //   {
      //   id: 'fieldUnit',
      //   name: '数据单位',
      //   component: 'meta-select',
      //   disabled:true,
      //   type: 'unit-type',
      //   colSpan: 12
      // },,
        {
        id: 'sourceId',
        name: '计算指标',
          // parent:'sourceType',
        component:{
          id:'data-select',
          valueKey:'ref',
          getDataUrl:()=>{
            return '/settings/model_export_ref/ref/data?modelId='+this.modelInfo.id+'&yearRelated=${yearRelated}';
          },
          load:(dataList)=>{
            let map = {};
            for(let item of dataList) {
              map[item.ref]=item;
            }
            this.computeUnitMap = map;
          }
        },
        colSpan: 24,
          // change:(val,data)=>{
          // console.log(val)
          // console.log(data)
          // if(this.computeUnitMap[val]) {
          //   data.sourceType = this.computeUnitMap[val];
          // } else {
          //   data.sourceType = '';
          // }
          // }
      },
        // {
        //   id: 'sourceType',
        //   name: '计算指标类型',
        //   component: {
        //     id: 'meta-select',
        //     type:'compute-type',
        //   },
        //   colSpan: 24,
        //
        // },
        // {
        //   id: 'extractType',
        //   name: '提取方式',
        //   component: {
        //     id: 'meta-select',
        //     type:'compute-data-extract-type',
        //   },
        //   colSpan: 24,
        //   isHide:(data)=>{
        //     if(!data.sourceId) {
        //       return true;
        //     }
        //     if(this.computeUnitMap[data.sourceId]&&this.computeUnitMap[data.sourceId].type=='compute') {
        //       return true;
        //     }
        //     return false;
        //   }
        // }
      ],

    }
  },

  created: function () {
    // const modelId = this.$route.params.id;

    this.loadModelList();
    // this.loadMetaMap('model-param-ref-source',(map)=>{
    //   this.refParamSourceMap=map;
    // })
  },
  computed:{
    tableMaxHeight(){
      if(!this.pageHeight) {
        return 500;
      }
      return this.pageHeight - 130;
    },
    modelQueryFields(){
      if(!this.modelInfo||!this.modelInfo.id) {
        return [];
      }
      return [{id:'modelId',name:'模型id',hide:true,defaultValue: this.modelInfo.id}];
    },
    fieldQueryFields(){
      if(!this.modelInfo||!this.modelInfo.id||!this.currentInputTable) {
        return [];
      }
      return [{id:'modelId',name:'模型id',hide:true,defaultValue: this.modelInfo.id},{id:'tableId',name:'分类id',hide:true,defaultValue:this.currentInputTable.id}];
    }
  },
  methods: {
    getCurrentTable(){
      return this.currentInputTable.id;
    },
    loadModelInfo: function (modelId) {
      this.currentInputTable = {};
      this.isLoading = true;
      this.$get("/model/" + modelId, {}, (response) => {
        let reload = true&&this.$refs["record_query_table"];
        this.modelInfo = response.data;
        this.$nextTick(()=>{
          if(this.$refs["record_query_table"]&&reload) {
            this.$refs["record_query_table"].reload();
          }
        })
      },(response)=>{
        this.isLoading = false;
      });
    },
    loadModelList: function () {
      this.isLoading = true;
      this.$get('/settings/model/publish/data', {}, (response) => {
        this.modelList = response.data;
        let modelInfo = this.modelList[0];
        for(let item of this.modelList) {
          if(item.id=='105f798a831d4d919662c96a3d13c59f') {
            modelInfo = item;
            break;
          }
        }
        this.queryConditon.id = modelInfo.id;
        this.loadModelInfo(modelInfo.id);
      },(response)=>{
        this.isLoading = false;
      });
    },
    loadInputFieldList: function (table) {
      // this.isFieldLoading = true;
      //第一次表格初始化不需要重新加载数据
      let reload = true&&this.$refs["record_field_query_table"];
      this.currentInputTable = table;
      this.$nextTick(()=>{
        if(this.$refs["record_field_query_table"]&&reload) {
          this.$refs["record_field_query_table"].reload();
        }

      })
      // this.$get("/field/data?tableId=" + table.id, {}, (response) => {
      //   let list = response.data;
      //   for (let item of list) {
      //     if (!item.paramSource) {
      //       item.paramSource = 'input';
      //     }
      //   }
      //   this.inputFieldList = list;
      //
      // }, () => {
      //   this.isFieldLoading = false;
      // });
    },



    //默认值是否是单个值
    isDefaultValueSingle(dataSource,dataId) {
      // if (!dataSource || dataSource == 'input') {
      //   return true;
      // }
      // if (!this.refParamIdMap[dataSource] || !this.refParamIdMap[dataSource][dataId]) {
      //   return true;
      // }
      // if (this.refParamIdMap[dataSource][dataId].yearRelated) {
      //   return false;
      // }
      if (this.refParamIdMap[dataId]&&this.refParamIdMap[dataId].yearRelated) {
          return false;
      }
      return true;
    },
    /**
     * 导出配置数据
     */
    exportConfig(){
      window.open(this.$ctx+'/settings/model_ref/export?modelId='+this.modelInfo.id);
    },
    /**
     * 导入配置数据
     */
    importConfig(){
      if(!this.configInfo.fileList||this.configInfo.fileList.length <1){
        this.$message.warning("请先上传配置文件");
        return;
      }
      const loading = this.openLoading('正在处理...');
      this.$post('/settings/model_ref/import',{modelId:this.modelInfo.id,fileId:this.configInfo.fileList[0].id},(response)=>{
        this.$message.success("导入成功")
        this.configInfo = {fileList: []};
        this.loadModelInfo(this.modelInfo.id);
      },(response)=>{
        loading.close();
        this.importConfigVisible = false;
      })
    }

  },

}
</script>
